package edu.tjpu.share.task;

import java.util.HashMap;
import java.util.List;

import org.phprpc.PHPRPC_Client;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.biz.IUserList;
import edu.tjpu.share.newui.UserList;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.po.UserVo;

public class UserListTask extends
		AsyncTask<HashMap<String, Object>, Integer, HashMap<String, Object>> {

	@Override
	protected HashMap<String, Object> doInBackground(
			HashMap<String, Object>... maps) {

		List<UserVo> userlist = null;
		Handler handler = (Handler) maps[0].get(Fields.HANDLER);
		Server serverinfo = (Server) maps[0].get(Fields.SERVER_INFO);
		int cid = (Integer) maps[0].get(Fields.CID);
		int gid = (Integer) maps[0].get(Fields.GID);
		int mid = (Integer) maps[0].get(Fields.MID);
		int uid = (Integer) maps[0].get(Fields.UID);

		StringBuilder sbhost = new StringBuilder();
		sbhost.append("http://");
		sbhost.append(serverinfo.getHost());
		sbhost.append(":");
		sbhost.append(serverinfo.getProt());
		sbhost.append("/ShareServer/servlet/UserListServlet");

		try {
			PHPRPC_Client userListClient = new PHPRPC_Client(sbhost.toString());
			IUserList iUserList = (IUserList) userListClient
					.useService(IUserList.class);
			userlist = iUserList.getUserList(gid, mid, cid, uid);
		} catch (Exception e) {
			Message msg = new Message();
			msg.what = Fields.NETWORK_CONNECTION_ERROR;
			handler.sendMessage(msg);
			return null;
		}

		HashMap<String, Object> outmap = new HashMap<String, Object>();
		outmap.put(Fields.USER_LIST, userlist);
		outmap.put(Fields.HANDLER, handler);
		return outmap;
	}

	@Override
	protected void onPostExecute(HashMap<String, Object> result) {
		super.onPostExecute(result);
		if (isCancelled()) {
			result = null;
		}
		if (result != null) {
			@SuppressWarnings("unchecked")
			List<UserVo> userList = (List<UserVo>) result.get(Fields.USER_LIST);
			Handler handler = (Handler) result.get(Fields.HANDLER);
			UserList.setUserList(userList);
			handler.sendEmptyMessage(0);
		}
	}

}
